<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace app\api\model\v1;

use think\Db;

/**
 * 小程序模型类
 */
class Api extends Base
{
    //初始化
    protected function initialize()
    {
        // 需要调用`Model`的`initialize`方法
        parent::initialize();
    }

    /**
     * 文档详情
     * @param int $aid 文档ID
     */
    public function getArchivesView($aid = '', $users = [])
    {
        $aid = intval($aid);
        $args = [$aid, $users];
        $cacheKey = 'api-' . md5(__CLASS__ . __FUNCTION__ . json_encode($args));
        $result = cache($cacheKey);
        if (true || empty($result)) {
            $detail = $this->getViewInfo($aid, $users);
            if (!empty($detail['detail'])) {
                if (0 <= $detail['detail']['arcrank']) { // 待审核稿件
                    $detail['detail']['title'] = htmlspecialchars_decode($detail['detail']['title']);
                    $add_time = $detail['detail']['add_time'];
                    $detail['detail']['add_time_format'] = $this->time_format($add_time);
                    $detail['detail']['add_time'] = date('Y-m-d H:i:s', $add_time); // 格式化发布时间，兼容早期开源小程序
                    $detail['detail']['content'] = $this->html_httpimgurl($detail['detail']['content'], true); // 转换内容图片为http路径

                    !empty($detail['product']) && $result['product'] = $detail['product']; // 推荐商品
                    !empty($detail['coupon_list']) && $result['coupon_list'] = $detail['coupon_list']; // 优惠券列表
                } else {
                    $detail['detail'] = [
                        'arcrank' => $detail['detail']['arcrank'],
                    ];
                }
            }

            $result['detail']['data'] = !empty($detail['detail']) ? $detail['detail'] : false;

            cache($cacheKey, $result, null, 'archives');
        }

        if (!empty($result['detail']['data'])) {
            // 浏览量
            Db::name('archives')->where(['aid' => $aid])->setInc('click');
            $result['detail']['data']['click'] += 1;
            eyou_statistics_data(1);
        }

        return $result;
    }

    /**
     * 获取单条文档记录
     * @author wengxianhu by 2017-7-26
     */
    private function getViewInfo($aid, $users = [])
    {
        $result = [];
        $field = 'a.aid,a.typeid,a.channel,a.title,a.subtitle,a.litpic,a.video_paths,a.video_times,a.author,a.click,a.arcrank,a.seo_title,a.seo_keywords,a.seo_description,a.users_price,a.market_price,a.users_free,a.old_price,a.stock_show,a.stock_count,a.prom_type,a.arc_level_id,a.downcount,a.add_time,a.attrlist_id,a.freight_fee_set,a.freight_fee_tpl,a.sales_show,a.sales_num,a.virtual_sales,a.goods_unit,b.typename';
        $detail = Db::name('archives')
            ->alias('a')
            ->field($field)
            ->join('arctype b', 'a.typeid = b.id', 'left')
            ->where([
                'a.aid' => $aid,
                'a.status' => 1,
                'a.is_del' => 0,
            ])
            ->find();
        if (!empty($detail)) {
            if (2 == $detail['channel']) {
                // 销售量+虚拟销量
                $detail['sales_num'] = intval($detail['sales_num']) + intval($detail['virtual_sales']);
                // 价格拆分
                if (!empty($detail['users_price'])) {
                    $detail['users_price'] = unifyPriceHandle($detail['users_price']);
                    $detail['users_price_arr'] = explode('.', $detail['users_price']);
                }
                // 视频处理
                $detail['video_paths'] = !empty($detail['video_paths']) ? $this->get_default_pic($detail['video_paths']) : '';
                if (!empty($detail['video_times'])) {
                    if (intval($detail['video_times']) < 60) $detail['video_times'] = '00′' . $detail['video_times'] . '″';
                }
                // 商品运费处理
                if (!empty($detail['freight_fee_set']) && 2 === intval($detail['freight_fee_set']) && !empty($detail['freight_fee_tpl'])) {
                    $where = [
                        'template_id' => intval($detail['freight_fee_tpl'])
                    ];
                    $freightTemplate = Db::name('shop_freight_template')->field('express_id, template_data, special_set, special_data')->where($where)->find();
                    // 配送公司
                    $expressID = !empty($freightTemplate['express_id']) ? intval($freightTemplate['express_id']) : 0;
                    $detail['express_name'] = Db::name('shop_express')->where(['express_id' => $expressID])->getField('express_name');
                    // 配送运费
                    $templateData = !empty($freightTemplate['template_data']) ? unserialize($freightTemplate['template_data']) : [];
                    $detail['freight_fee'] = !empty($templateData[0]['freight_fee']) ? unifyPriceHandle($templateData[0]['freight_fee']) : '包邮';
                    // 特殊区域
                    if (!empty($freightTemplate['special_set']) && 1 === intval($freightTemplate['special_set'])) {
                        $detail['special_title'] = '不配送区域';
                    } else if (!empty($freightTemplate['special_set']) && 2 === intval($freightTemplate['special_set'])) {
                        $detail['special_title'] = '配送区域';
                    }
                    $specialData = !empty($freightTemplate['special_data']) ? unserialize($freightTemplate['special_data']) : [];
                    $detail['special_names'] = !empty($specialData['special_names']) ? $specialData['special_names'] : [];
                } else {
                    // 配送运费
                    $detail['freight_fee'] = '包邮';
                    $detail['express_name'] = '商家配送';
                    $detail['special_title'] = '配送区域';
                    $detail['special_names'] = '全国配送';
                }
                // 商品标签处理
                $where = [
                    'a.aid' => intval($detail['aid'])
                ];
                $goodsLabel = Db::name('product_label')->alias('a')
                    ->field('b.*')
                    ->where($where)
                    ->join('__LABEL_TYPES__ b', 'a.types_id = b.types_id', 'LEFT')
                    ->select();
                $goodsLabel = group_same_key($goodsLabel, 'types_value');
                $marketingLabel = !empty($goodsLabel[1][0]['types_names']) ? $goodsLabel[1][0]['types_names'] : '';
                $detail['marketingLabel'] = $marketingLabel;
                $serviceLabel = !empty($goodsLabel[2]) ? $goodsLabel[2] : [];
                $detail['serviceLabel'] = $serviceLabel;
            }

            // 模型标题处理
            $channeltype_row = \think\Cache::get('extra_global_channeltype');
            $channeltypeInfo = !empty($channeltype_row[$detail['channel']]) ? $channeltype_row[$detail['channel']] : [];
            $detail['channel_ntitle'] = !empty($channeltypeInfo['ntitle']) ? $channeltypeInfo['ntitle'] : '文章';
            $detail['seo_title'] = $this->set_arcseotitle($detail['title'], $detail['seo_title']); // seo标题
            $detail['litpic'] = $this->get_default_pic($detail['litpic']); // 默认封面图
            // $detail['forward'] = Db::name('users_forward')->where('aid',$aid)->count(); // 转发记录，废弃了，有需要就通过请求传参进行判断是否要查表返回数据，或者写成标签apiForward
            $detail['content'] = '';
            if (1 == $detail['channel']) { // 文章模型
                unset($detail['sales_num']);
                unset($detail['stock_show']);
                unset($detail['stock_count']);
                unset($detail['prom_type']);
                unset($detail['downcount']);
            } else if (2 == $detail['channel']) { // 产品模型
                unset($detail['users_free']);
                unset($detail['downcount']);
                /*产品参数*/
                $productAttrModel = new \app\home\model\ProductAttr;
                $attr_list = $productAttrModel->getShopProductAttr($aid, 'a.attr_id,a.attr_name,b.attr_value,b.aid');
                $attr_list = !empty($attr_list[$aid]) ? $attr_list[$aid] : [];
                foreach ($attr_list as $key => $val) {
                    $val['attr_value'] = htmlspecialchars_decode($val['attr_value']);
                    unset($val['aid']);
                    $attr_list[$key] = $val;
                }
                $detail['attr_list'] = !empty($attr_list) ? $attr_list : false;   //产品默认参数

                /*规格数据*/
                $detail['spec_attr'] = $this->getSpecAttr($aid, $users);
                /* END */

                // 产品相册
                $productImgModel = new \app\home\model\ProductImg;
                $image_list = $productImgModel->getProImg($aid, 'aid,image_url,intro');
                $image_list = !empty($image_list[$aid]) ? $image_list[$aid] : [];
                foreach ($image_list as $key => $val) {
                    $val['image_url'] = $this->get_default_pic($val['image_url']);
                    isset($val['intro']) && $val['intro'] = htmlspecialchars_decode($val['intro']);
                    $image_list[$key] = $val;
                }
                $detail['image_list'] = !empty($image_list) ? $image_list : false;

                /*可控制的主表字段列表*/
                $detail['ifcontrolRow'] = Db::name('channelfield')->field('id,name')->where([
                    'channel_id' => $detail['channel'],
                    'ifmain' => 1,
                    'ifeditable' => 1,
                    'ifcontrol' => 0,
                    'status' => 1,
                ])->getAllWithIndex('name');

                // 设置默认原价
                $detail['old_price'] = $detail['users_price'];
                $detail['product_num'] = 1;
                $detail['spec_value_id'] = '';

                $detail['cart_total_num'] = 0;
                if (!empty($users['users_id'])) {
                    //购物车数量
                    $detail['cart_total_num'] = Db::name('shop_cart')->where(['users_id' => $users['users_id']])->sum('product_num');
                }
            } else if (3 == $detail['channel']) { // 图集模型
                unset($detail['users_price']);
                unset($detail['users_free']);
                unset($detail['old_price']);
                unset($detail['sales_num']);
                unset($detail['stock_show']);
                unset($detail['stock_count']);
                unset($detail['prom_type']);
                unset($detail['downcount']);
                // 图集相册
                $imagesUploadModel = new \app\home\model\ImagesUpload;
                $image_list = $imagesUploadModel->getImgUpload($aid, 'aid,image_url,intro');
                $image_list = !empty($image_list[$aid]) ? $image_list[$aid] : [];
                foreach ($image_list as $key => $val) {
                    $val['image_url'] = $this->get_default_pic($val['image_url']);
                    isset($val['intro']) && $val['intro'] = htmlspecialchars_decode($val['intro']);
                    $image_list[$key] = $val;
                }
                $detail['image_list'] = !empty($image_list) ? $image_list : false;
            } else if (4 == $detail['channel']) { // 下载模型
                unset($detail['users_price']);
                unset($detail['users_free']);
                unset($detail['old_price']);
                unset($detail['sales_num']);
                unset($detail['stock_show']);
                unset($detail['stock_count']);
                unset($detail['prom_type']);
                if (0 == $detail['arc_level_id']) {
                    $downloadFileModel = new \app\home\model\DownloadFile;
                    $down_list = $downloadFileModel->getDownFile($aid);
                    $down_list = !empty($down_list[$aid]) ? $down_list[$aid] : [];
                    foreach ($down_list as $key => $val) {
                        $val['file_url'] = handle_subdir_pic($val['file_url']);
                        $down_list[$key] = $val;
                    }
                } else {
                    $down_list = false;
                }
                $detail['down_list'] = !empty($down_list) ? $down_list : false;
            } else if (5 == $detail['channel']) { // 视频模型
                unset($detail['sales_num']);
                unset($detail['stock_show']);
                unset($detail['stock_count']);
                unset($detail['prom_type']);
                unset($detail['downcount']);
                // 视频附件列表
                $mediaFileModel = new \app\home\model\MediaFile;
                $media_list = $mediaFileModel->getMediaFile($aid);
                foreach ($media_list as $key => $val) {
                    $val['file_url'] = handle_subdir_pic($val['file_url'], 'media');
                    $media_list[$key] = $val;
                }
                $detail['media_list'] = !empty($media_list) ? $media_list : false;
            } else {
                unset($detail['users_price']);
                unset($detail['users_free']);
                unset($detail['old_price']);
                unset($detail['sales_num']);
                unset($detail['stock_show']);
                unset($detail['stock_count']);
                unset($detail['prom_type']);
                unset($detail['downcount']);
            }

            // 获取自定义字段的数据
            $customField = [];
            $addtableName = $channeltypeInfo['table'] . '_content';
            $detailRow = Db::name($addtableName)->field('id,aid,add_time,update_time', true)->where('aid', $aid)->find();
            if (!empty($detailRow)) {
                $fieldLogic = new \app\home\logic\FieldLogic();
                $detailExt = $fieldLogic->getChannelFieldList($detailRow, $detail['channel']); // 自定义字段的数据格式处理
                if (empty($channeltypeInfo['ifsystem'])) { // 自定义模型
                    // 如果存在自定义字段content，默认作为文档的正文内容。
                    // 如果不存在，将获取第一个html类型的内容，作为文档的正文内容。
                    if (!isset($detailExt['content'])) {
                        $contentField = Db::name('channelfield')->where([
                            'channel_id' => $detail['channel'],
                            'dtype' => 'htmltext',
                        ])->getField('name');
                        $detailExt['content'] = !empty($detailExt[$contentField]) ? $detailExt[$contentField] : '';
                    }
                }
                $detail['content'] = $detailExt['content'];
                unset($detailExt['content']);

                // 手机端详情内容
                if (isset($detailExt['content_ey_m'])) {
                    $detail['content'] = $detailExt['content_ey_m'];
                    unset($detailExt['content_ey_m']);
                }

                if (!empty($detailExt)) {
                    $field = 'name, title, dtype';
                    $customField = Db::name('channelfield')->field($field)->where([
                        'name' => ['IN', array_keys($detailExt)],
                        'channel_id' => $detail['channel'],
                        'ifeditable' => 1
                    ])->getAllWithIndex('name');
                    if (!empty($customField)) {
                        foreach ($customField as $key => $value) {
                            if ('img' == $value['dtype']) {
                                $customField[$key]['value'] = $this->get_default_pic($detailExt[$key]);
                            } else if ('media' == $value['dtype']) {
                                $customField[$key]['value'] = $this->get_default_pic($detailExt[$key]);
                            } else if ('imgs' == $value['dtype']) {
                                foreach ($detailExt[$key] as $kk => $vv) {
                                    $detailExt[$key][$kk]['image_url'] = $this->get_default_pic($vv['image_url']);
                                }
                                $customField[$key]['value'] = $detailExt[$key];
                            } else {
                                $customField[$key]['value'] = $detailExt[$key];
                            }
                        }
                    }
                }
                $customField = array_values($customField);
            }
            $detail['customField'] = !empty($customField) ? $customField : false;

            $result['detail'] = $detail;
        }

        return $result;
    }

    /**
     * 留言栏目表单
     * @param int $typeid 栏目ID
     */
    public function getGuestbookForm($typeid)
    {
        $typeid = intval($typeid);
        if (empty($typeid)) {
            $typeid = Db::name('arctype')->where([
                'current_channel' => 8,
                'is_del' => 0,
                'status' => 1,
            ])->getField('id');
        }

        $attr_list = array();
        $typename = '';
        if (0 < $typeid) {
            $detail = Db::name('arctype')->field('id,id as typeid,typename,seo_title,seo_keywords,seo_description')->where([
                'id' => $typeid,
            ])->find();
            $detail['seo_title'] = $this->set_arcseotitle($detail['typename'], $detail['seo_title']);
            $attr_list = Db::name('GuestbookAttribute')->field('attr_id,attr_name,attr_input_type,attr_values')
                ->where([
                    'typeid' => $typeid,
                    'is_del' => 0,
                ])
                ->order('sort_order asc, attr_id asc')
                ->select();
            foreach ($attr_list as $key => $val) {
                if (in_array($val['attr_input_type'], array(1, 3, 4))) {
                    $val['attr_values'] = explode(PHP_EOL, $val['attr_values']);
                    $attr_list[$key] = $val;
                }
            }
        }

        /*表单令牌*/
        $token_name = md5('guestbookform_token_' . $typeid . md5(getTime() . uniqid(mt_rand(), TRUE)));
        $token_value = md5($_SERVER['REQUEST_TIME_FLOAT']);
        $session_path = \think\Config::get('session.path');
        $session_file = ROOT_PATH . $session_path . "/sess_" . $token_name;
        $fp = fopen($session_file, "w+");
        if (!empty($fp)) {
            if (fwrite($fp, $token_value)) {
                fclose($fp);
            }
        } else {
            file_put_contents($session_file, $token_value);
        }
        /*end*/

        $result = array(
            'detail' => $detail,
            'attr_list' => $attr_list,
            'token' => [
                'name' => '__token__' . $token_name,
                'value' => $token_value,
            ],
        );

        return $result;
    }

    /**
     *  给指定留言添加表单值到 guestbook_attr
     * @param int $aid 留言id
     * @param int $typeid 留言栏目id
     */
    public function saveGuestbookAttr($post, $aid, $typeid)
    {
        $attrArr = [];
        foreach ($post as $k => $v) {
            if (!strstr($k, 'attr_')) {
                continue;
            }

            $attr_id = str_replace('attr_', '', $k);
            is_array($v) && $v = implode(PHP_EOL, $v);
            $v = trim($v);
            $adddata = array(
                'aid' => $aid,
                'attr_id' => $attr_id,
                'attr_value' => $v,
                'add_time' => getTime(),
                'update_time' => getTime(),
            );
            Db::name('GuestbookAttr')->add($adddata);
        }
    }

    // 获取指定商品的规格数据
    public function getSpecAttr($aid = null, $users = [], $order2 = '')
    {
        $ReturnData = $SpecData = $SpecValue = $SelectSpecData = [];
        if (empty($aid)) return $ReturnData;
        if (empty($users['level_discount'])) $users['level_discount'] = 100;
        // 会员折扣率
        $SelectSpecData['users_discount'] = (intval($users['level_discount']) / 100);

        $SpecWhere = [
            'aid' => $aid,
            'spec_is_select' => 1,
        ];
        $order = 'spec_value_id asc, spec_id asc';
        $field = '*, false checked';
        $ProductSpecData = Db::name('product_spec_data')->field($field)->where($SpecWhere)->order($order)->select();
        if (!empty($ProductSpecData)) {
            $ProductSpecData = group_same_key($ProductSpecData, 'spec_mark_id');
            foreach ($ProductSpecData as $key => $value) {
                // $value[0]['checked'] = true;
                $SpecData[] = [
                    'spec_value_id' => $value[0]['spec_value_id'],
                    'spec_mark_id' => $value[0]['spec_mark_id'],
                    'spec_name' => $value[0]['spec_name'],
                    'spec_data_new' => $value,
                ];
            }

            unset($SpecWhere['spec_is_select']);
            $order2 = !empty($order2) ? $order2 : 'seckill_price asc,spec_price asc';
            $ProductSpecValue = Db::name('product_spec_value')->where($SpecWhere)->order($order2)->select();

            if (!empty($ProductSpecValue)) {
                // 默认的规格值，取价格最低者
                $SelectSpecData['spec_value_id'] = explode('_', $ProductSpecValue[0]['spec_value_id']);

                // 若存在规格并且价格存在则覆盖原有价格
                $SelectSpecData['users_price'] = sprintf("%.2f", strval($ProductSpecValue[0]['spec_price']) * strval($SelectSpecData['users_discount']));

                // 产品原价
                $SelectSpecData['old_price'] = $ProductSpecValue[0]['spec_price'];

                // 若存在规格并且库存存在则覆盖原有库存
                $SelectSpecData['stock_count'] = $ProductSpecValue[0]['spec_stock'];

                // 价格及库存
                $SpecValue = $ProductSpecValue;
            }
            foreach ($SpecData as $key => $value) {
                foreach ($value['spec_data_new'] as $kk => $vv) {
                    // 追加默认规格class
                    if (in_array($vv['spec_value_id'], $SelectSpecData['spec_value_id'])) {
                        $SpecData[$key]['spec_data_new'][$kk]['checked'] = true;
                    }
                }
            }
        }

        $ReturnData = [
            'spec_data' => $SpecData,
            'spec_value' => $SpecValue,
            'select_spec_data' => $SelectSpecData
        ];

        return $ReturnData;
    }

    /**
     * 获取数量
     * 优惠券/收藏/足迹/评价
     */
    public function getSomeCount($user, $type = '')
    {
        $count = 0;
        if (false == $user || '' == $type) {
            return $count;
        } else {
            switch ($type) {
                case 'coupon': // 优惠券
                    $where['users_id'] = $user['users_id'];
                    $where['use_status'] = 0;
                    $count = Db::name('shop_coupon_use')->where($where)->count();
                    break;
                case 'collect'; // 收藏
                    $where['a.users_id'] = $user['users_id'];
                    $where['b.status'] = 1;
                    $where['b.is_del'] = 0;
                    $count = Db::name('users_collection')
                        ->alias('a')
                        ->join('archives b', 'a.aid = b.aid', 'left')
                        ->where($where)->count();
                    break;
                case 'footprint'; // 足迹
                    $where['a.users_id'] = $user['users_id'];
                    $where['b.status'] = 1;
                    $where['b.is_del'] = 0;
                    $count = Db::name('users_footprint')
                        ->alias('a')
                        ->join('archives b', 'a.aid = b.aid', 'left')
                        ->where($where)->count();
                    break;
                case 'comment'; // 评论
                    $where['users_id'] = $user['users_id'];
                    $count = Db::name('shop_order_comment')->where($where)->count();
                    break;
            }

            return $count;
        }
    }

    /**
     * 获取评论列表
     */
    public function getGoodsCommentList($param = [])
    {
        $page = empty($param['page']) ? 1 : $param['page'];
        $type = empty($param['type']) ? 'all' : $param['type'];
        $pagesize = empty($param['pagesize']) ? config('paginate.list_rows') : $param['pagesize'];
        $total_score = empty($param['total_score']) ? '' : $param['total_score'];
        $goods_id = $param['aid'];
        $field = 'a.*,u.nickname,u.head_pic';
        // 筛选条件
        $condition = [
            'a.product_id' => $goods_id,
            'a.is_show' => 1,
        ];
        if (!empty($param['total_score'])) $condition['a.total_score'] = $param['total_score'];
        if ('img' == $type) $condition['a.upload_img'] = ['neq', ''];

        $args = [$goods_id, $page, $pagesize, $total_score];
        $cacheKey = 'api-' . md5(__CLASS__ . __FUNCTION__ . json_encode($args));
        if (true || empty($result)) {
            $paginate = array(
                'page' => $page,
            );
            $pages = Db::name('shop_order_comment')
                ->field($field)
                ->alias('a')
                ->join('users u', 'a.users_id = u.users_id', 'left')
                ->where($condition)
                ->order('a.add_time desc')
                ->paginate($pagesize, false, $paginate);
            $result = $pages->toArray();

            foreach ($result['data'] as $key => $val) {
                $val['head_pic'] = get_default_pic($val['head_pic'], true);
                if (isset($val['add_time'])) {
                    $val['add_time'] = date('Y-m-d H:i:s', $val['add_time']);
                }
                if (!empty($val['upload_img'])) {
                    $val['upload_img'] = unserialize($val['upload_img']);
                    $val['upload_img'] = explode(',', $val['upload_img']);
                    foreach ($val['upload_img'] as $k => $v) {
                        $val['upload_img'][$k] = get_default_pic($v, true);
                    }
                }
                if (!empty($val['content'])) {
                    $val['content'] = unserialize($val['content']);
                }
                $result['data'][$key] = $val;
            }
            $score_type = Db::name('shop_order_comment')
                ->where([
                    'product_id' => $goods_id,
                    'is_show' => 1,
                ])->field('count(*) as count,total_score')
                ->group('total_score')
                ->getAllWithIndex('total_score');
            $result['count']['goods'] = isset($score_type[1]) ? $score_type[1]['count'] : 0;
            $result['count']['middle'] = isset($score_type[2]) ? $score_type[2]['count'] : 0;
            $result['count']['bad'] = isset($score_type[3]) ? $score_type[3]['count'] : 0;
            $result['count']['all'] = $result['count']['goods'] + $result['count']['middle'] + $result['count']['bad'];

            cache($cacheKey, $result, null, 'getGoodsCommentList');
            $condition['a.upload_img'] = ['neq', ''];
            $result['have_img_count'] = Db::name('shop_order_comment')->alias('a')->where($condition)->count();
        }
        return $result;
    }

    /**
     * 获取限时折扣商品详情
     */
    public function GetDiscountGoods($aid = 0, $users = [])
    {
        $aid = intval($aid);
        $args = [$aid, $users];
        $cacheKey = 'api-' . md5(__CLASS__ . __FUNCTION__ . json_encode($args));
        $result = cache($cacheKey);
        if (true || empty($result)) {
            $detail = $this->getDiscountInfo($aid, $users);
            if (!empty($detail['detail'])) {
                if (0 <= $detail['detail']['arcrank']) { // 待审核稿件
                    $detail['detail']['title'] = htmlspecialchars_decode($detail['detail']['title']);
                    $detail['detail']['add_time'] = date('Y-m-d H:i:s', $detail['detail']['add_time']); // 格式化发布时间
                    $detail['detail']['content'] = $this->html_httpimgurl($detail['detail']['content'], true); // 转换内容图片为http路径
                } else {
                    $detail['detail'] = [
                        'arcrank' => $detail['detail']['arcrank'],
                    ];
                }
            }

            $result = [
                'detail' => [
                    'data' => !empty($detail['detail']) ? $detail['detail'] : false,
                ],
                'product' => !empty($detail['product']) ? $detail['product'] : [],
                'coupon_list' => !empty($detail['coupon_list']) ? $detail['coupon_list'] : [],
            ];

            cache($cacheKey, $result, null, 'archives');
        }

        return $result;
    }

    /**
     * 获取限时折扣商品记录
     */
    private function getDiscountInfo($aid, $users = [])
    {
        $where = [
            'a.status' => 1,
            'a.is_del' => 0,
            'a.aid' => $aid,
        ];
        $result = [];
        $detail = Db::name('discount_goods')
            ->alias('a')
            ->field('a.discount_gid,a.discount_stock,a.discount_price,a.sales,a.virtual_sales,a.is_sku,b.sales_actual,c.*')
            ->where($where)
            ->join('discount_active_goods b', 'a.aid = b.aid', 'left')
            ->join('archives c', 'a.aid = c.aid', 'left')
            ->find();

        if (!empty($detail)) {
            // 模型标题处理
            $channeltype_row = \think\Cache::get('extra_global_channeltype');
            $channeltypeInfo = !empty($channeltype_row[$detail['channel']]) ? $channeltype_row[$detail['channel']] : [];
            $detail['channel_ntitle'] = !empty($channeltypeInfo['ntitle']) ? $channeltypeInfo['ntitle'] : '文章';
            $detail['seo_title'] = $this->set_arcseotitle($detail['title'], $detail['seo_title']); // seo标题
            $detail['litpic'] = $this->get_default_pic($detail['litpic']); // 默认封面图
            $detail['content'] = '';

            unset($detail['users_free']);
            unset($detail['downcount']);

            /*产品参数*/
            if (!empty($detail['attrlist_id'])) { // 新版参数
                $productAttrModel = new \app\home\model\ProductAttr;
                $attr_list = $productAttrModel->getShopProductAttr($aid, 'a.attr_id,a.attr_name,b.attr_value,b.aid');
            }
            $attr_list = !empty($attr_list[$aid]) ? $attr_list[$aid] : [];
            foreach ($attr_list as $key => $val) {
                $val['attr_value'] = htmlspecialchars_decode($val['attr_value']);
                unset($val['aid']);
                $attr_list[$key] = $val;
            }
            $detail['attr_list'] = !empty($attr_list) ? $attr_list : false;


            /*规格数据*/
            $detail['spec_attr'] = $this->getSpecAttr($aid, $users, 'discount_price asc,spec_price asc');
            /* END */

            // 产品相册
            $productImgModel = new \app\home\model\ProductImg;
            $image_list = $productImgModel->getProImg($aid, 'aid,image_url,intro');
            $image_list = !empty($image_list[$aid]) ? $image_list[$aid] : [];
            foreach ($image_list as $key => $val) {
                $val['image_url'] = $this->get_default_pic($val['image_url']);
                isset($val['intro']) && $val['intro'] = htmlspecialchars_decode($val['intro']);
                $image_list[$key] = $val;
            }

            $detail['image_list'] = !empty($image_list) ? $image_list : false;
            /*可控制的主表字段列表*/
            $detail['ifcontrolRow'] = Db::name('channelfield')->field('id,name')->where([
                'channel_id' => $detail['channel'],
                'ifmain' => 1,
                'ifeditable' => 1,
                'ifcontrol' => 0,
                'status' => 1,
            ])->getAllWithIndex('name');

            // 设置默认原价
            $detail['old_price'] = $detail['users_price'];
            $detail['product_num'] = 1;
            $detail['spec_value_id'] = '';

            $detail['cart_total_num'] = 0;
            if (!empty($users['users_id'])) {
                //购物车数量
                $detail['cart_total_num'] = Db::name('shop_cart')->where(['users_id' => $users['users_id']])->sum('product_num');
            }

            // 获取自定义字段的数据
            $customField = [];
            $detailExt = Db::name($channeltypeInfo['table'] . '_content')->field('id,aid,add_time,update_time', true)->where('aid', $aid)->find();
            if (!empty($detailExt)) {
                $fieldLogic = new \app\home\logic\FieldLogic();
                $detailExt = $fieldLogic->getChannelFieldList($detailExt, $detail['channel']); // 自定义字段的数据格式处理
                if (empty($channeltypeInfo['ifsystem'])) { // 自定义模型
                    // 如果存在自定义字段content，默认作为文档的正文内容。
                    // 如果不存在，将获取第一个html类型的内容，作为文档的正文内容。
                    if (!isset($detailExt['content'])) {
                        $contentField = Db::name('channelfield')->where([
                            'channel_id' => $detail['channel'],
                            'dtype' => 'htmltext',
                        ])->getField('name');
                        $detailExt['content'] = !empty($detailExt[$contentField]) ? $detailExt[$contentField] : '';
                    }
                }
                $detail['content'] = $detailExt['content'];
                unset($detailExt['content']);

                if (!empty($detailExt)) {
                    $field = 'name, title, dtype';
                    $customField = Db::name('channelfield')->field($field)->where([
                        'name' => ['IN', array_keys($detailExt)],
                        'channel_id' => $detail['channel'],
                        'ifeditable' => 1
                    ])->getAllWithIndex('name');
                    if (!empty($customField)) {
                        foreach ($customField as $key => $value) {
                            if ('img' == $value['dtype']) {
                                $customField[$key]['value'] = $this->get_default_pic($detailExt[$key]);
                            } else if ('media' == $value['dtype']) {
                                $customField[$key]['value'] = $this->get_default_pic($detailExt[$key]);
                            } else if ('imgs' == $value['dtype']) {
                                foreach ($detailExt[$key] as $kk => $vv) {
                                    $detailExt[$key][$kk]['image_url'] = $this->get_default_pic($vv['image_url']);
                                }
                                $customField[$key]['value'] = $detailExt[$key];
                            } else {
                                $customField[$key]['value'] = $detailExt[$key];
                            }
                        }
                    }
                }
                $customField = array_values($customField);
            }
            $detail['customField'] = !empty($customField) ? $customField : false;

            // 浏览量
            Db::name('archives')->where(['aid' => $aid])->setInc('click');
            $detail['click'] += 1;

            $result['detail'] = $detail;
        }

        return $result;
    }

    //添加文章评论
    public function addArticleComment($param = [], $users = [])
    {
        $users_level_id = !empty($users['level_id']) ? $users['level_id'] : 0;//0-游客
        $comment_level_data = Db::name('weapp_comment_level')->where('users_level_id', $users_level_id)->find();
        if (empty($comment_level_data['is_comment'])) {
            return ['code' => 0, 'msg' => '您没有评论权限'];
        }
        if (!empty($comment_level_data['is_review'])) {
            $param['is_review'] = 0;
        } else {
            $param['is_review'] = 1;
        }
        $param['add_time'] = getTime();
        $param['update_time'] = getTime();
        $param['users_id'] = !empty($users['users_id']) ? $users['users_id'] : 0;
        $param['username'] = !empty($users['username']) ? $users['username'] : '游客';
        $param['provider'] = !empty($param['provider']) ? $param['provider'] : 'weixin';
        $param['users_ip'] = clientIP();
        $comment_id = Db::name('weapp_comment')->insertGetId($param);
        if (false !== $comment_id) {
            $data = ['code' => 1, 'is_show' => 0];
            if (empty($param['is_review'])) {
                $msg = '评论成功，进入待审核中';
            } else {
                $msg = '评论成功';
                $comment = Db::name('weapp_comment')
                    ->alias('a')
                    ->field('a.*,b.head_pic,b.nickname,b.sex')
                    ->join('users b', 'a.users_id = b.users_id', 'left')
                    ->find($comment_id);
                $comment['head_pic'] = $this->get_head_pic($comment['head_pic'], false, $comment['sex']);
                $comment['add_time_format'] = $this->time_format($comment['add_time']);
                $comment['add_time'] = date('Y-m-d', $comment['add_time']);
                $data['comment'] = $comment;
                $data['is_show'] = 1;
            }
            $data['msg'] = $msg;

            return $data;
        }
        return ['code' => 0, 'msg' => '添加评论失败'];
    }

    /**
     * 索引页
     */
    public function getRepertory($page = 1)
    {
        $paginate = array(
            'page' => $page,
        );
        $allow_release_channel = config('global.allow_release_channel');
        $pages = Db::name('archives')->field('aid,typeid,title,channel,update_time')
            ->where([
                'channel' => ['IN', $allow_release_channel],
                'arcrank' => ['EGT', 0],
                'is_del' => 0,
            ])
            ->order('update_time desc')
            ->paginate(100, false, $paginate);

        $list = array();
        foreach ($pages->items() as $key => $val) {
            $path = '';
            if (1 == $val['channel']) {
                $path = '/pages/archives/article/view?aid=' . $val['aid'] . '&typeid=' . $val['typeid'];
            } else if (2 == $val['channel']) {
                $path = '/pages/archives/product/view?aid=' . $val['aid'] . '&typeid=' . $val['typeid'];
            } else if (3 == $val['channel']) {
                $path = '/pages/archives/images/view?aid=' . $val['aid'] . '&typeid=' . $val['typeid'];
            } else if (4 == $val['channel']) {
                $path = '/pages/archives/download/view?aid=' . $val['aid'] . '&typeid=' . $val['typeid'];
            } else if (5 == $val['channel']) {
                $path = '/pages/archives/media/view?aid=' . $val['aid'] . '&typeid=' . $val['typeid'];
            } else if (6 == $val['channel']) {
                $path = '/pages/archives/single/view?typeid=' . $val['typeid'];
            } else if (7 == $val['channel']) {
                $path = '/pages/archives/special/view?aid=' . $val['aid'] . '&typeid=' . $val['typeid'];
            } else {
                $path = '/pages/archives/custom/view?aid=' . $val['aid'] . '&typeid=' . $val['typeid'];
            }

            $arr = [
                'title' => $val['title'],
                'path' => $path,
                'releaseDate' => MyDate('Y-m-d H:i:s', $val['update_time']),
            ];
            $list[] = $arr;
        }
        $result = array(
            'totalPage' => $pages->lastPage(),
            'current' => $page,
            'list' => $list,
        );
        return $result;
    }

    /**
     * 微信小程序消息模板列表
     * @return [type] [description]
     */
    public function getWeixinTemplateList($where = [])
    {
        $map = ['template_code' => ['gt', 0], 'is_open' => 1];
        $where = array_merge($map, $where);
        $template_list = Db::name('weixin_template')->where($where)->order('send_scene asc')->getAllWithIndex('send_scene');
        return !empty($template_list) ? $template_list : [];
    }

    /**
     * 发送微信小程序订阅消息
     */
    public function sendWeixinNotice($result_id, $send_scene = 0, $users = [])
    {
        $template_info = Db::name('weixin_template')->where(['send_scene' => $send_scene])->find();
        if (empty($template_info)) {
            return ['code' => 0, 'msg' => '小程序消息模板不存在'];
        } else if (empty($template_info['is_open'])) {
            return ['code' => 0, 'msg' => '小程序消息模板没开启'];
        }

        $tokenData = getWeixinAccessToken(true);
        if (!empty($tokenData['code'])) {
            $redata = $this->weixinTemplateKeywords($result_id, $template_info);
            $openid = Db::name('wx_users')->where(['users_id' => $users['users_id']])->value('openid');
            $post_data = [
                'template_id' => $template_info['template_id'],
                'page' => !empty($redata['pagepath']) ? $redata['pagepath'] : '/pages/index/index',
                'touser' => $openid,
                'data' => $redata['data'],
                'miniprogram_state' => 'formal',
                'lang' => 'zh_CN',
            ];
            $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $tokenData['access_token'];
            $response = httpRequest($url, 'POST', json_encode($post_data, JSON_UNESCAPED_UNICODE));
            $params = json_decode($response, true);
            if (isset($params['errcode']) && empty($params['errcode'])) {
                return ['code' => 1, 'msg' => '发送成功'];
            }
        }
        $msg = !empty($params['errmsg']) ? $params['errmsg'] : $tokenData['msg'];
        return ['code' => 0, 'msg' => $msg];
    }

    private function weixinTemplateKeywords($result_id, $template_info)
    {
        $data = [];
        $pagepath = '';
        $tpl_data = json_decode($template_info['tpl_data'], true);
        $keywordsList = [];
        if (!empty($tpl_data['keywordsList'])) {
            foreach ($tpl_data['keywordsList'] as $key => $val) {
                $keywordsList[$val['rule'] . $val['kid']] = $val;
            }
        }
        $send_scene = $template_info['send_scene'];
        if (5 == $send_scene) { // 订单支付成功通知
            $pagepath = "/pages/order/detail?order_id={$result_id}";
            $orderInfo = Db::name('shop_order')->where(['order_id' => $result_id])->find();
            $orderDetailsInfo = Db::name('shop_order_details')->where(['order_id' => $orderInfo['order_id']])->order('details_id asc')->select();
            $product_name_new = msubstr($orderDetailsInfo[0]['product_name'], 0, 15);
            if ($product_name_new == $orderDetailsInfo[0]['product_name'] && count($orderDetailsInfo) == 1) {
                $product_name = $product_name_new;
            } else {
                $product_name = $product_name_new . '等...';
            }
            $data = [
                'character_string1' => [
                    'value' => $orderInfo['order_code'],
                ],
                'thing3' => [
                    'value' => $product_name,
                ],
                'amount13' => [
                    'value' => "¥{$orderInfo['order_amount']}",
                ],
                'date2' => [
                    'value' => MyDate('Y-m-d H:i:s', $orderInfo['pay_time']),
                ],
                // 'thing7' => [
                //     'value' => '感谢您的支持，祝您购物愉快！',
                // ],
            ];
        } else if (6 == $send_scene) { // 订单发货通知
            $pagepath = "/pages/order/detail?order_id={$result_id}";
            $orderInfo = Db::name('shop_order')->where(['order_id' => $result_id])->find();
            $orderDetailsInfo = Db::name('shop_order_details')->where(['order_id' => $orderInfo['order_id']])->order('details_id asc')->select();
            $product_name_new = msubstr($orderDetailsInfo[0]['product_name'], 0, 15);
            if ($product_name_new == $orderDetailsInfo[0]['product_name'] && count($orderDetailsInfo) == 1) {
                $product_name = $product_name_new;
            } else {
                $product_name = $product_name_new . '等...';
            }
            $data = [
                'character_string1' => [
                    'value' => $orderInfo['order_code'],
                ],
                'thing2' => [
                    'value' => $product_name,
                ],
                'thing7' => [
                    'value' => $orderInfo['express_name'],
                ],
                'character_string4' => [
                    'value' => $orderInfo['express_order'],
                ],
                'date5' => [
                    'value' => MyDate('Y-m-d H:i:s', $orderInfo['express_time']),
                ],
            ];
        } else if (8 == $send_scene) { // 订单完成通知
            $pagepath = "/pages/order/detail?order_id={$result_id}";
            $orderInfo = Db::name('shop_order')->where(['order_id' => $result_id])->find();
            $orderDetailsInfo = Db::name('shop_order_details')->where(['order_id' => $orderInfo['order_id']])->order('details_id asc')->select();
            $product_name_new = msubstr($orderDetailsInfo[0]['product_name'], 0, 15);
            if ($product_name_new == $orderDetailsInfo[0]['product_name'] && count($orderDetailsInfo) == 1) {
                $product_name = $product_name_new;
            } else {
                $product_name = $product_name_new . '等...';
            }
            $data = [
                'character_string1' => [
                    'value' => $orderInfo['order_code'],
                ],
                'thing6' => [
                    'value' => $product_name,
                ],
                'phrase2' => [
                    'value' => !empty($keywordsList['phrase2']) ? $keywordsList['phrase2']['example'] : '订单已签收',
                ],
                'date7' => [
                    'value' => $orderInfo['express_order'],
                ],
                'date5' => [
                    'value' => MyDate('Y-m-d H:i:s', $orderInfo['confirm_time']),
                ],
            ];
        } else if (9 == $send_scene) { // 订单关闭通知
            $pagepath = "/pages/order/detail?order_id={$result_id}";
            $orderInfo = Db::name('shop_order')->where(['order_id' => $result_id])->find();
            $orderDetailsInfo = Db::name('shop_order_details')->where(['order_id' => $orderInfo['order_id']])->order('details_id asc')->select();
            $product_name_new = msubstr($orderDetailsInfo[0]['product_name'], 0, 15);
            if ($product_name_new == $orderDetailsInfo[0]['product_name'] && count($orderDetailsInfo) == 1) {
                $product_name = $product_name_new;
            } else {
                $product_name = $product_name_new . '等...';
            }
            $data = [
                'character_string2' => [
                    'value' => $orderInfo['order_code'],
                ],
                'thing6' => [
                    'value' => $product_name,
                ],
                'amount3' => [
                    'value' => "¥{$orderInfo['order_amount']}",
                ],
                'date4' => [
                    'value' => MyDate('Y-m-d H:i:s', $orderInfo['add_time']),
                ],
                'phrase5' => [
                    'value' => !empty($keywordsList['phrase5']) ? $keywordsList['phrase5']['example'] : '订单已关闭',
                ],
            ];
        } else if (10 == $send_scene) { // 商家同意退款
            $pagepath = "/pages/order/service/detail?service_id={$result_id}";
            $orderServiceInfo = Db::name('shop_order_service')->where(['service_id' => $result_id])->find();
            $product_name = msubstr($orderServiceInfo['product_name'], 0, 15);
            $data = [
                'amount6' => [
                    'value' => "¥{$orderServiceInfo['refund_balance']}",
                ],
                'thing3' => [
                    'value' => $product_name,
                ],
                'character_string2' => [
                    'value' => $orderServiceInfo['refund_code'],
                ],
                'thing1' => [
                    'value' => !empty($keywordsList['thing1']) ? $keywordsList['thing1']['example'] : '您的退款将退回账户余额，请注意查收',
                ],
            ];
        } else if (12 == $send_scene) { // 商家拒绝退款
            $pagepath = "/pages/order/service/detail?service_id={$result_id}";
            $orderServiceInfo = Db::name('shop_order_service')->where(['service_id' => $result_id])->find();
            $product_name = msubstr($orderServiceInfo['product_name'], 0, 15);
            $data = [
                'amount6' => [
                    'value' => "¥{$orderServiceInfo['refund_balance']}",
                ],
                'thing3' => [
                    'value' => $product_name,
                ],
                'character_string2' => [
                    'value' => $orderServiceInfo['refund_code'],
                ],
                'thing1' => [
                    'value' => !empty($orderServiceInfo['refund_note']) ? $orderServiceInfo['refund_note'] : '商品不支持退货退款',
                ],
            ];
        } else if (13 == $send_scene) { // 充值成功通知
            $pagepath = "/pages/user/records/records";
            $result = Db::name('users_money')->where(['moneyid' => $result_id])->find();
            $data = [
                'amount3' => [
                    'value' => "¥{$result['actual_money']}",
                ],
                'amount6' => [
                    'value' => "¥{$result['users_money']}",
                ],
                'time4' => [
                    'value' => MyDate('Y-m-d H:i:s', $result['add_time']),
                ],
                'thing5' => [
                    'value' => !empty($keywordsList['thing5']) ? $keywordsList['thing5']['example'] : '余额充值，如未到账可联系客服',
                ],
            ];
        }

        return [
            'data' => $data,
            'pagepath' => $pagepath,
        ];
    }

    /**
     * 发送微信公众号模板消息
     */
    public function sendWechatNotice($result_id, $send_scene = 0, $users = [])
    {
        if (empty($users['wechat_open_id'])) {
            return ['code' => 0, 'msg' => '该用户还没关注公众号'];
        }

        $template_info = Db::name('wechat_template')->where(['send_scene' => $send_scene])->find();
        if (empty($template_info)) {
            return ['code' => 0, 'msg' => '公众号消息模板不存在'];
        } else if (empty($template_info['is_open'])) {
            return ['code' => 0, 'msg' => '公众号消息模板没开启'];
        }

        $tokenData = getWechatAccessToken(true);
        if (!empty($tokenData['code'])) {
            $redata = $this->wechatTemplateKeywords($result_id, $template_info);
            $post_data = [
                'template_id' => $template_info['template_id'],
                'touser' => $users['wechat_open_id'],
                'data' => $redata['data'],
                'client_msg_id' => md5(json_encode($redata)),
            ];
            if (!empty($tokenData['weixin_appid'])) {
                $post_data['miniprogram'] = [
                    'appid' => $tokenData['weixin_appid'],
                ];
                !empty($redata['pagepath']) && $post_data['miniprogram']['pagepath'] = $redata['pagepath'];
            }
            $web_status = tpCache('web.web_status');
            if (!empty($web_status)) {
                $post_data['url'] = !empty($redata['gourl']) ? $redata['gourl'] : request()->domain() . $this->root_dir;
            }
            $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $tokenData['access_token'];
            $response = httpRequest($url, 'POST', json_encode($post_data, JSON_UNESCAPED_UNICODE));
            $params = json_decode($response, true);
            if (isset($params['errcode']) && empty($params['errcode'])) {
                return ['code' => 1, 'msg' => '发送成功'];
            }
        }
        $msg = !empty($params['errmsg']) ? $params['errmsg'] : $tokenData['msg'];
        return ['code' => 0, 'msg' => $msg];
    }

    private function wechatTemplateKeywords($result_id, $template_info)
    {
        $data = [];
        $gourl = $pagepath = "";
        $tpl_data = json_decode($template_info['tpl_data'], true);
        $keywordsList = [];
        if (!empty($tpl_data['keywordsList'])) {
            foreach ($tpl_data['keywordsList'] as $key => $val) {
                $keywordsList[$val['rule']] = $val;
            }
        }
        $send_scene = $template_info['send_scene'];
        if (5 == $send_scene) { // 订单支付成功通知
            $pagepath = "/pages/order/detail?order_id={$result_id}";
            $gourl = url('user/Shop/shop_order_details', ['order_id' => $result_id]);
            $orderInfo = Db::name('shop_order')->where(['order_id' => $result_id])->find();
            $orderDetailsInfo = Db::name('shop_order_details')->where(['order_id' => $orderInfo['order_id']])->order('details_id asc')->select();
            $product_name_new = msubstr($orderDetailsInfo[0]['product_name'], 0, 22);
            if ($product_name_new == $orderDetailsInfo[0]['product_name'] && count($orderDetailsInfo) == 1) {
                $product_name = $product_name_new;
            } else {
                $product_name = $product_name_new . '等...';
            }
            $data = [
                'first' => [
                    'value' => $template_info['template_title'],
                ],
                'keyword1' => [
                    'value' => $orderInfo['order_code'],
                ],
                'keyword2' => [
                    'value' => $product_name,
                ],
                'keyword3' => [
                    'value' => count($orderDetailsInfo),
                ],
                'keyword4' => [
                    'value' => "¥{$orderInfo['order_amount']}",
                ],
                'keyword5' => [
                    'value' => MyDate('Y-m-d H:i:s', $orderInfo['pay_time']),
                ],
                'remark' => [
                    'value' => !empty($keywordsList['remark']) ? $keywordsList['remark']['example'] : '我们将尽快安排发货，祝您购物愉快！',
                ],
            ];
        } else if (6 == $send_scene) { // 订单发货通知
            $pagepath = "/pages/order/detail?order_id={$result_id}";
            $gourl = url('user/Shop/shop_order_details', ['order_id' => $result_id]);
            $orderInfo = Db::name('shop_order')->where(['order_id' => $result_id])->find();
            // 地址显示中文名字
            $orderInfo['country'] = '中国';
            $orderInfo['province'] = get_province_name($orderInfo['province']);
            $orderInfo['city'] = get_city_name($orderInfo['city']);
            $orderInfo['district'] = get_area_name($orderInfo['district']);
            $data = [
                'first' => [
                    'value' => $template_info['template_title'],
                ],
                'keyword1' => [
                    'value' => $orderInfo['order_code'],
                ],
                'keyword2' => [
                    'value' => MyDate('Y-m-d H:i:s', $orderInfo['express_time']),
                ],
                'keyword3' => [
                    'value' => $orderInfo['express_name'],
                ],
                'keyword4' => [
                    'value' => $orderInfo['express_order'],
                ],
                'keyword5' => [
                    'value' => "{$orderInfo['consignee']}  {$orderInfo['mobile']}  {$orderInfo['province']}{$orderInfo['city']}{$orderInfo['district']}{$orderInfo['address']}",
                ],
                'remark' => [
                    'value' => !empty($keywordsList['remark']) ? $keywordsList['remark']['example'] : '请保持收件手机畅通！',
                ],
            ];
        } else if (8 == $send_scene) { // 订单完成通知
            $pagepath = "/pages/order/detail?order_id={$result_id}";
            $gourl = url('user/Shop/shop_order_details', ['order_id' => $result_id]);
            $orderInfo = Db::name('shop_order')->where(['order_id' => $result_id])->find();
            $orderDetailsInfo = Db::name('shop_order_details')->where(['order_id' => $orderInfo['order_id']])->order('details_id asc')->select();
            $product_name_new = msubstr($orderDetailsInfo[0]['product_name'], 0, 22);
            if ($product_name_new == $orderDetailsInfo[0]['product_name'] && count($orderDetailsInfo) == 1) {
                $product_name = $product_name_new;
            } else {
                $product_name = $product_name_new . '等...';
            }
            $data = [
                'first' => [
                    'value' => $template_info['template_title'],
                ],
                'keyword1' => [
                    'value' => $orderInfo['order_code'],
                ],
                'keyword2' => [
                    'value' => $product_name,
                ],
                'keyword3' => [
                    'value' => MyDate('Y-m-d H:i:s', $orderInfo['confirm_time']),
                ],
                'remark' => [
                    'value' => !empty($keywordsList['remark']) ? $keywordsList['remark']['example'] : '如有任何疑问，请联系客服！',
                ],
            ];
        } else if (9 == $send_scene) { // 订单关闭通知
            $pagepath = "/pages/order/detail?order_id={$result_id}";
            $gourl = url('user/Shop/shop_order_details', ['order_id' => $result_id]);
            $orderInfo = Db::name('shop_order')->where(['order_id' => $result_id])->find();
            $orderDetailsInfo = Db::name('shop_order_details')->where(['order_id' => $orderInfo['order_id']])->order('details_id asc')->select();
            $product_name_new = msubstr($orderDetailsInfo[0]['product_name'], 0, 22);
            if ($product_name_new == $orderDetailsInfo[0]['product_name'] && count($orderDetailsInfo) == 1) {
                $product_name = $product_name_new;
            } else {
                $product_name = $product_name_new . '等...';
            }
            $data = [
                'first' => [
                    'value' => $template_info['template_title'],
                ],
                'keyword1' => [
                    'value' => $product_name,
                ],
                'keyword2' => [
                    'value' => $orderInfo['order_code'],
                ],
                'keyword3' => [
                    'value' => (4 == $orderInfo['order_status']) ? '未付款订单超时自动关闭' : '未付款订单已取消交易',
                ],
                'remark' => [
                    'value' => !empty($keywordsList['remark']) ? $keywordsList['remark']['example'] : '感谢您的选择，请及时查看确认。',
                ],
            ];
        } else if (10 == $send_scene) { // 商家同意退款
            $pagepath = "/pages/order/service/detail?service_id={$result_id}";
            $gourl = url('user/Shop/after_service_details', ['service_id' => $result_id]);
            $orderServiceInfo = Db::name('shop_order_service')->where(['service_id' => $result_id])->find();
            $product_name = msubstr($orderServiceInfo['product_name'], 0, 22);
            $data = [
                'first' => [
                    'value' => $template_info['template_title'],
                ],
                'keyword1' => [
                    'value' => $orderServiceInfo['refund_code'],
                ],
                'keyword2' => [
                    'value' => $product_name,
                ],
                'remark' => [
                    'value' => !empty($keywordsList['remark']) ? $keywordsList['remark']['example'] : '如有任何疑问，请联系客服！',
                ],
            ];
        } else if (12 == $send_scene) { // 商家拒绝退款
            $pagepath = "/pages/order/service/detail?service_id={$result_id}";
            $gourl = url('user/Shop/after_service_details', ['service_id' => $result_id]);
            $orderServiceInfo = Db::name('shop_order_service')->where(['service_id' => $result_id])->find();
            $product_name = msubstr($orderServiceInfo['product_name'], 0, 22);
            $data = [
                'first' => [
                    'value' => $template_info['template_title'],
                ],
                'keyword1' => [
                    'value' => "¥{$orderServiceInfo['refund_balance']}",
                ],
                'keyword2' => [
                    'value' => $product_name,
                ],
                'keyword3' => [
                    'value' => $orderServiceInfo['refund_code'],
                ],
                'keyword4' => [
                    'value' => $orderServiceInfo['refund_note'],
                ],
                'remark' => [
                    'value' => !empty($keywordsList['remark']) ? $keywordsList['remark']['example'] : '如有任何疑问，请联系客服！',
                ],
            ];
        } else if (13 == $send_scene) { // 充值成功通知
            $pagepath = "/pages/user/records/records";
            $gourl = url('user/Pay/pay_consumer_details');
            $result = Db::name('users_money')->where(['moneyid' => $result_id])->find();
            $give_money = $result['actual_money'] - $result['money'];
            $give_money_str = ($give_money > 0) ? " (赠送金额￥{$give_money})" : "";
            $data = [
                'first' => [
                    'value' => $template_info['template_title'],
                ],
                'keyword1' => [
                    'value' => MyDate('Y-m-d H:i:s', $result['add_time']),
                ],
                'keyword2' => [
                    'value' => "¥{$result['money']}{$give_money_str}",
                ],
                'keyword3' => [
                    'value' => !empty($keywordsList['keyword3']) ? $keywordsList['keyword3']['example'] : '充值成功',
                ],
                'remark' => [
                    'value' => !empty($keywordsList['remark']) ? $keywordsList['remark']['example'] : '如有任何疑问，请联系客服！',
                ],
            ];
        } else if (15 == $send_scene) { // 用户支付通知（商家）
            $pagepath = "/pages/order/detail?order_id={$result_id}";
            $gourl = url('user/Shop/shop_order_details', ['order_id' => $result_id]);
            $orderInfo = Db::name('shop_order')->where(['order_id' => $result_id])->find();
            $data = [
                'first' => [
                    'value' => $template_info['template_title'],
                ],
                'keyword1' => [
                    'value' => "¥{$orderInfo['order_amount']}",
                ],
                'keyword2' => [
                    'value' => $orderInfo['order_code'],
                ],
                'remark' => [
                    'value' => !empty($keywordsList['remark']) ? $keywordsList['remark']['example'] : '您好，顾客已支付成功，请及时处理。',
                ],
            ];
        } else if (16 == $send_scene) { // 用户订单完成通知（商家）
            $pagepath = "/pages/order/detail?order_id={$result_id}";
            $gourl = url('user/Shop/shop_order_details', ['order_id' => $result_id]);
            $orderInfo = Db::name('shop_order')->where(['order_id' => $result_id])->find();
            $data = [
                'first' => [
                    'value' => $template_info['template_title'],
                ],
                'keyword1' => [
                    'value' => $orderInfo['order_code'],
                ],
                'keyword2' => [
                    'value' => MyDate('Y-m-d H:i:s', $orderInfo['confirm_time']),
                ],
                'remark' => [
                    'value' => !empty($keywordsList['remark']) ? $keywordsList['remark']['example'] : '感谢您的使用，祝您生意兴隆。',
                ],
            ];
        } else if (17 == $send_scene) { // 用户申请维权通知（商家）
            $pagepath = "/pages/order/service/detail?service_id={$result_id}";
            $gourl = url('user/Shop/after_service_details', ['service_id' => $result_id]);
            $orderInfo = Db::name('shop_order_service')->where(['order_id' => $result_id])->find();
            $service_name = '仅换货';
            if (2 == $orderInfo['service_type']) {
                $service_name = '退货退款';
            } else if (3 == $orderInfo['service_type']) {
                $service_name = '仅退款';
            }
            $data = [
                'first' => [
                    'value' => $template_info['template_title'],
                ],
                'keyword1' => [
                    'value' => $orderInfo['refund_code'],
                ],
                'keyword2' => [
                    'value' => $service_name,
                ],
                'keyword3' => [
                    'value' => MyDate('Y-m-d H:i:s', $orderInfo['add_time']),
                ],
                'remark' => [
                    'value' => !empty($keywordsList['remark']) ? $keywordsList['remark']['example'] : '如有疑问，请尽快联系买家！',
                ],
            ];
        } else if (18 == $send_scene) { // 用户已退货通知（商家）
            $pagepath = "/pages/order/service/detail?service_id={$result_id}";
            $gourl = url('user/Shop/after_service_details', ['service_id' => $result_id]);
            $orderInfo = Db::name('shop_order_service')->where(['order_id' => $result_id])->find();
            $orderDetailsInfo = Db::name('shop_order_details')->where(['order_id' => $orderInfo['order_id']])->order('details_id asc')->select();
            $product_name_new = msubstr($orderDetailsInfo[0]['product_name'], 0, 22);
            if ($product_name_new == $orderDetailsInfo[0]['product_name'] && count($orderDetailsInfo) == 1) {
                $product_name = $product_name_new;
            } else {
                $product_name = $product_name_new . '等...';
            }
            $users_delivery = unserialize($orderInfo['users_delivery']);
            $users_delivery['time'] = !empty($users_delivery['time']) ? $users_delivery['time'] : getTime();
            $data = [
                'first' => [
                    'value' => $template_info['template_title'],
                ],
                'keyword1' => [
                    'value' => $orderInfo['refund_code'],
                ],
                'keyword2' => [
                    'value' => $product_name,
                ],
                'keyword3' => [
                    'value' => !empty($users_delivery['name']) ? $users_delivery['name'] : '',
                ],
                'keyword4' => [
                    'value' => !empty($users_delivery['code']) ? $users_delivery['code'] : '',
                ],
                'keyword5' => [
                    'value' => MyDate('Y-m-d H:i:s', $users_delivery['time']),
                ],
                'remark' => [
                    'value' => !empty($keywordsList['remark']) ? $keywordsList['remark']['example'] : '请注意查收，记得及时处理哦！',
                ],
            ];
        }

        return [
            'data' => $data,
            'pagepath' => $pagepath,
            'gourl' => $gourl,
        ];
    }

    /**
     * 下发小程序和公众号统一的服务消息
     */
    // public function sendUniformNotice($result_id, $send_scene = 0, $users = [])
    // {
    //     $template_info = Db::name('weixin_template')->where(['send_scene'=>$send_scene])->find();
    //     if (empty($template_info)) {
    //         return ['code'=>0, 'msg'=>'小程序消息模板不存在'];
    //     } else if (empty($template_info['is_open'])) {
    //         return ['code'=>0, 'msg'=>'小程序消息模板没开启'];
    //     }

    //     $tokenData = getWeixinAccessToken(true);
    //     if (!empty($tokenData['code'])) {
    //         $data = $this->uniformTemplateKeywords($result_id, $template_info);
    //         $openid = Db::name('wx_users')->where(['users_id'=>$users['users_id']])->value('openid');
    //         $post_data = [
    //             'touser' => $openid,
    //             'weapp_template_msg' => $data['weapp_template_msg'],
    //             'mp_template_msg' => $data['mp_template_msg'],
    //         ];
    //         $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token=".$tokenData['access_token'];
    //         $response = httpRequest($url, 'POST', json_encode($post_data, JSON_UNESCAPED_UNICODE));
    //         $params = json_decode($response, true);
    //         if (isset($params['errcode']) && empty($params['errcode'])) {
    //             return ['code'=>1, 'msg'=>'发送成功'];
    //         }
    //     }
    //     $msg = !empty($params['errmsg']) ? $params['errmsg'] : $tokenData['msg'];
    //     return ['code'=>0, 'msg'=>$msg];
    // }

}
